﻿using System;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using Core.Unity;
using Services;
using System.Linq;
using System.Data.Entity;
using System.Collections.Generic;
using System.Reflection;
using ViewModels;

namespace Commands {
    /// <summary>
    /// 保存数据
    /// </summary>
    public class SaveDataCommand : CommandBase {
        private IXContainer _hook;
        private CommandManagerWpf _CommandManagerWpf;
        private IDisplayTable _IDisplayTable;

        public override void OnCreate(object hook) {
            base.OnCreate(hook);
            _hook = hook as IXContainer;
            _IDisplayTable = _hook.Resolve<IDisplayTable>();
        }
        public override void OnClick(object parameter) {
            Timer_Elapsed(null, null);

            //System.Timers.Timer timer = new System.Timers.Timer();
            //timer.Interval = 15000;
            //timer.Elapsed += Timer_Elapsed;
            //timer.Start();
        }

        void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
            _hook.Resolve<ITextHint>().AddText(Environment.NewLine + DateTime.Now.ToString() + "------ 开始获取数据。 ------");
            Dictionary<string, object> allObjs = _hook.GetAll();
            foreach (var item in allObjs) {
                if (item.Value is IInfoService) {
                    IInfoService captureDataService = item.Value as IInfoService;
                    captureDataService.AfterQueryData -= this.AfterQueryData;
                    captureDataService.AfterQueryData += this.AfterQueryData;
                    MethodInfo queryDataMethodInfo = captureDataService.GetType().GetMethod("QueryData");
                    queryDataMethodInfo.Invoke(item.Value, null);
                }
            }
        }

        private void AfterQueryData(object sender, ReceivedDataEventArgs e) {
            if (e.Error != null) {
                _hook.Resolve<ITextHint>().AddText(DateTime.Now.ToString() + " 获取到 " + sender.GetType().FullName + " 数据失败。");
                return;
            }
            IInfoService captureDataService = sender as IInfoService;
            _hook.Resolve<ITextHint>().AddText(DateTime.Now.ToString() + " 获取到 " + sender.GetType().FullName + " 数据。");
            captureDataService.SaveData(e.Data);
        }

        void OnModelCreatingEvent(ref DbModelBuilder modelBuilder) {
            Dictionary<string, object> allObjs = _hook.GetAll();
            foreach (var item in allObjs) {
                if (item.Value is IInfoService) {
                    (item.Value as IInfoService).OnModelCreating(ref modelBuilder);
                }
            }
        }
    }
}
